
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package horsechess.server.data;

import horsechess.server.gui.GUIServer;
import java.util.ArrayList;
import java.util.Vector;

/**
 *
 * @author Administrator
 */
public class Server {

    public int port = 7777;
    public String serverAddr = "225.4.5.6";
    private BroadcastServer broadcastServer;
    private ServerHandler serverHandler;
    public Thread threadBroadcastHandler;
    public Thread threadServerHandler;
    // Which port should we send to
    private GUIServer guiServer;

    public Server(GUIServer guiServer) {

        this.guiServer = guiServer;
        broadcastServer = new BroadcastServer(port, serverAddr, guiServer);
        serverHandler = new ServerHandler(guiServer);
    }

    public Vector<String> getRooms() {
        Vector<String> vects = new Vector<String>();
        for (int i = 0; i < ServerHandler.listOfRoom.size(); i++) {
            RoomManager roomManager = ServerHandler.listOfRoom.get(i);
            vects.add(roomManager.getRoomName());
        }
        return vects;
    }

    public RoomManager getRoom(String roomName) {
        //ArrayList clients=new ArrayList();
        for (int i = 0; i < serverHandler.listOfRoom.size(); i++) {
            RoomManager roomManager = serverHandler.listOfRoom.elementAt(i);
            if (roomManager.getRoomName().equalsIgnoreCase(roomName)) {
                return roomManager;
            }
        }
        return null;
    }

    public ArrayList<ClientHandler> listClients(String roomName) {
        //ArrayList clients=new ArrayList();
        for (int i = 0; i < serverHandler.listOfRoom.size(); i++) {
            RoomManager roomManager = serverHandler.listOfRoom.elementAt(i);
            if (roomManager.getRoomName().equalsIgnoreCase(roomName)) {
                return roomManager.clients;
            }
        }
        return null;
    }

    public static Vector<RoomManager> listOfRoom() {
        return ServerHandler.listOfRoom;
    }

    public void broadcast(String ipAddress) {
        serverAddr = ipAddress;
        threadBroadcastHandler = new Thread(broadcastServer);
        threadBroadcastHandler.start();
    }

    public void startReceivingServer() {
        threadServerHandler = new Thread(serverHandler);
        threadServerHandler.start();
    }
    public boolean shutdownServer(){

        boolean isSuccess=true;
        for (int i = 0; i < serverHandler.listOfRoom.size(); i++) {
            RoomManager room=serverHandler.listOfRoom.get(i);
            if(room.disconnectAllPlayers())
                System.out.println("All client in "+room.getRoomName()+" have been disconnected successfully");
            else isSuccess=false;
        }
        if(isSuccess)
        {
             threadBroadcastHandler.stop();
            threadServerHandler.stop();
        }
        return isSuccess;
    }
}
